#! /usr/bin/env python
# -*- coding: utf8 -*-

from ots2 import *

import fittness


class cli:
    def __init__(self):
        self.__cli = OTSClient(fittness.OTS[0], fittness.OTS[1], fittness.OTS[2], fittness.OTS[3])

    def put_row(self, table, condition, pk, columns):
        try:
            consumed = self.__cli.put_row(table, condition, pk, columns)
        except OTSServiceError, e:
            if 'OTSConditionCheckFail' == e.get_error_code():
                return -1
            else:
                print e
                return -2
        return 0

    def update_row(self, table, condition, pk, columns):
        try:
            consumed = self.__cli.update_row(table, condition, pk, columns)
        except OTSServiceError, e:
            if 'OTSConditionCheckFail' == e.get_error_code():
                return -1
            else:
                print e
                return -2
        return 0

    def delete_row(self, table, condition, pk):
        try:
            consumed = self.__cli.delete_row(table, condition, pk)
        except OTSServiceError, e:
            if 'OTSConditionCheckFail' == e.get_error_code():
                return -1
            else:
                print e
                return -2
        return 0

    def get_row(self, table, pk, columns):
        consumed, pks, row = self.__cli.get_row(table, pk, columns)
        return row

    def get_range(self, table, direction, pk_begin, pk_end, columns, limit=5000):
        consumed, next_pk, rows = self.__cli.get_range(table, direction, pk_begin, pk_end, columns, limit)
        i = 0
        while 0 == len(rows) and next_pk is not None:
            consumed, next_pk, rows = self.__cli.get_range(table, direction, next_pk, pk_end, columns, limit)
            i += 1
            if 1000 < i:
                break
        for i in range(len(rows)):
            rows[i][1].update(rows[i][0])
            rows[i] = rows[i][1]
        return (rows, next_pk)

    def create_table(self, meta, throughput):
        self.__cli.create_table(meta, throughput)

    def delete_table(self, table_name):
        self.__cli.delete_table(table_name)
